using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using WCS.Infrastructure.Attr;
using Microsoft.Extensions.Configuration;
using WCS.Infrastructure.Dto.Common.Options;
using WCS.Infrastructure.Dto.Request.Ai;
using WCS.Infrastructure.Dto.Response.Ai;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Service.Interface;

namespace WCS.Service.Instance
{
    /// <summary>
    /// 文件说明：混元 AI 对话服务实现
    /// 作用：封装对外部混元 chat/completions 的 HTTP 请求与统一返回
    /// 作者：系统自动生成
    /// 日期：2025-11-19
    /// </summary>
    [Inject]
    public class HunyuanService : IHunyuanService
    {
        private readonly IConfiguration _configuration;
        private readonly HttpClient _httpClient;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration">配置读取器</param>
        public HunyuanService(IConfiguration configuration)
        {
            _configuration = configuration;
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 发送对话请求至混元，并返回统一结果
        /// </summary>
        /// <param name="dto">对话请求参数</param>
        /// <param name="ct">取消令牌</param>
        /// <returns>统一返回对象，成功 code=0，data 为混元响应</returns>
        /// <exception cref="Exception">网络错误或解析错误时抛出（由全局异常中间件兜底）</exception>
        public async Task<ApiResult> ChatAsync(ChatRequestDto dto, CancellationToken ct = default)
        {
            // 读取配置
            var baseUrl = _configuration["Hunyuan:BaseUrl"] ?? "https://api.hunyuan.cloud.tencent.com/v1";
            var apiKey = _configuration["Hunyuan:ApiKey"];
            var defaultModel = _configuration["Hunyuan:DefaultModel"] ?? "hunyuan-turbos-latest";
            var enableEnhancement = _configuration["Hunyuan:EnableEnhancement"];
            var timeoutSecondsStr = _configuration["Hunyuan:TimeoutSeconds"];

            if (int.TryParse(timeoutSecondsStr, out var timeoutSeconds) && timeoutSeconds > 0)
            {
                _httpClient.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
            }

            // 兜底模型与开关
            dto.model ??= defaultModel;
            if (dto.enable_enhancement == null && bool.TryParse(enableEnhancement, out var ee))
            {
                dto.enable_enhancement = ee;
            }

            // 组装请求
            var requestUrl = $"{baseUrl.TrimEnd('/')}/chat/completions";
            var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);

            var jsonOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            var payload = JsonSerializer.Serialize(dto, jsonOptions);
            request.Content = new StringContent(payload, Encoding.UTF8, "application/json");

            // 发送请求
            var response = await _httpClient.SendAsync(request, ct);
            var text = await response.Content.ReadAsStringAsync(ct);

            if (!response.IsSuccessStatusCode)
            {
                return new ApiResult
                {
                    code = ApiCode.fail,
                    message = text
                };
            }

            // 解析响应
            ChatResponseDto? data = null;
            try
            {
                data = JsonSerializer.Deserialize<ChatResponseDto>(text, jsonOptions);
            }
            catch (Exception ex)
            {
                // 解析失败返回错误信息
                return new ApiResult
                {
                    code = ApiCode.fail,
                    message = $"解析混元响应失败: {ex.Message}"
                };
            }

            return new ApiResult
            {
                code = ApiCode.ok,
                data = data
            };
        }

        /// <summary>
        /// 发送流式对话请求至混元，并返回原始 HTTP 响应以便控制器直接转发 SSE。
        /// </summary>
        /// <param name="dto">对话请求参数，需包含 stream=true</param>
        /// <param name="ct">取消令牌</param>
        /// <returns>外部服务的原始响应对象（内容类型 text/event-stream）</returns>
        /// <exception cref="Exception">网络错误时抛出（由全局异常中间件兜底）</exception>
        public async Task<HttpResponseMessage> ChatStreamRawAsync(ChatRequestDto dto, CancellationToken ct = default)
        {
            var baseUrl = _configuration["Hunyuan:BaseUrl"] ?? "https://api.hunyuan.cloud.tencent.com/v1";
            var apiKey = _configuration["Hunyuan:ApiKey"];
            var defaultModel = _configuration["Hunyuan:DefaultModel"] ?? "hunyuan-turbos-latest";
            var timeoutSecondsStr = _configuration["Hunyuan:TimeoutSeconds"];

            if (int.TryParse(timeoutSecondsStr, out var timeoutSeconds) && timeoutSeconds > 0)
            {
                _httpClient.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
            }

            dto.model ??= defaultModel;
            dto.stream = true; // 强制开启流式

            var requestUrl = $"{baseUrl.TrimEnd('/')}/chat/completions";
            var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);

            var jsonOptions = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            var payload = JsonSerializer.Serialize(dto, jsonOptions);
            request.Content = new StringContent(payload, Encoding.UTF8, "application/json");

            var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
            return response;
        }
    }
}
